<?php

namespace app\admin\controller\qingdongams\synchronizate;

use addons\qingdongams\model\Form;
use app\common\controller\Backend;
use addons\qingdongams\model\Fauser as FauserModel;
use addons\qingdongams\model\Field;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\CustomerOther;
use addons\qingdongams\model\Leads;
use addons\qingdongams\model\LeadsOther;
use addons\qingdongams\model\Contacts;
use think\Db;
/**
 * Fa会员同步
 */
class Fauser extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $fauser = FauserModel::where(array('user_id'=>$v['id']))->value('id');
                $list[$k]['user_status'] = 0;
                //用户已同步
                if($fauser){
                    $list[$k]['user_status'] = 1;
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 单个同步
     * @param null $ids
     * @return string
     */
    public function edit($ids = null){

        if ($this->request->isPost()) {
            $data             = $this->request->post('row/a');
            $dataArr             = $this->request->post('rows/a');
            $type = $data['type'];
            $source =$data['source'];
            $staff_id = $data['staff_id'];
            $remarks = '';
            $userinfo = $this->model->where(array('id'=>$ids))->find();
            Db::startTrans();
            //客户
            if($type == 0){
                $oterinfo = array();
                if($dataArr){
                    if(isset($dataArr['contract_status']['user'][0])){
                        $userinfo[$dataArr['contract_status']['user'][0]] = is_numeric($userinfo[$dataArr['contract_status']['user'][0]]) ? $userinfo[$dataArr['contract_status']['user'][0]] : 0;
                    }

                    $coutomer =array(
                        'name'=>isset($dataArr['name']['user'][0]) ? $userinfo[$dataArr['name']['user'][0]] :$userinfo['username'],
                        'subname'=>isset($dataArr['subname']['user'][0]) ? $userinfo[$dataArr['subname']['user'][0]] : $userinfo['nickname'],
                        'level'=>isset($dataArr['level']['user'][0]) ? $userinfo[$dataArr['level']['user'][0]] : $userinfo['level'],
                        'source'=>isset($dataArr['source']['user'][0]) ? $userinfo[$dataArr['source']['user'][0]] : $source,
                        'contract_status'=>isset($dataArr['contract_status']['user'][0]) ? $userinfo[$dataArr['contract_status']['user'][0]] : 0,
                        'industry'=>isset($dataArr['industry']['user'][0]) ? $userinfo[$dataArr['industry']['user'][0]] : '',
                        'create_staff_id'=>$staff_id,
                        'owner_staff_id'=>$staff_id,
                    );

                    foreach($dataArr as $k=>$v){
                        if(strpos($k,'other_') !== false){
                            $oterinfo[] = array(
                                'key'=>$k,
                                'value'=>$userinfo[$v['user'][0]]
                            );
                        }
                    }

                }else{
                    $coutomer =array(
                        'name'=>$userinfo['username'],
                        'subname'=>$userinfo['nickname'],
                        'level'=>$userinfo['level'],
                        'source'=>$source,
                        'remarks'=>$remarks,
                        'create_staff_id'=>$staff_id,
                        'owner_staff_id'=>$staff_id,
                    );

                }
                $resultCus = Customer::create($coutomer);
                if(!$resultCus){
                    Db::rollback();
                    $this->error('同步失败');
                }
                $insetId = Customer::getLastInsID();

                if($oterinfo){
                    $oterinfo = array_column($oterinfo,'value','key');
                    $oterinfo = json_encode($oterinfo,JSON_UNESCAPED_UNICODE);
                    $resoter = array(
                        'id'=> $insetId,
                        'otherdata'=>$oterinfo
                        );
                    CustomerOther::create($resoter);
                }

                $contacts = array(
                    'customer_id'=>$insetId,
                    'is_major'=>1,
                    'name'=>$userinfo['username'],
                    'subname'=>$userinfo['nickname'],
                    'email'=>$userinfo['email'],
                    'mobile'=>$userinfo['mobile'],
                    'create_staff_id'=>$staff_id,
                    'owner_staff_id'=>$staff_id,
                );
                $resultCon = Contacts::create($contacts);
                if(!$resultCon){
                    Db::rollback();
                    $this->error('同步失败');
                }

            }else{
                $oterinfo = array();
                //线索
                if($dataArr){
                    if(isset($dataArr['gender']['user'][0])){
                        $userinfo[$dataArr['gender']['user'][0]] = is_numeric($userinfo[$dataArr['gender']['user'][0]]) ? $userinfo[$dataArr['gender']['user'][0]] : 0;
                    }
                    if(isset($dataArr['level']['user'][0])){
                        $userinfo[$dataArr['level']['user'][0]] = is_numeric($userinfo[$dataArr['level']['user'][0]]) ? $userinfo[$dataArr['level']['user'][0]] : 0;
                    }
                    $lead =array(
                        'name'=>isset($dataArr['name']['user'][0]) ? $userinfo[$dataArr['name']['user'][0]] : $userinfo['username'],
                        'sex'=>isset($dataArr['gender']['user'][0]) ? $userinfo[$dataArr['gender']['user'][0]] : $userinfo['gender'],
                        'level'=>isset($dataArr['level']['user'][0]) ? $userinfo[$dataArr['level']['user'][0]] : $userinfo['level'],
                        'source'=>isset($dataArr['source']['user'][0]) ? $userinfo[$dataArr['source']['user'][0]] : $source,
                        'remarks'=>isset($dataArr['remarks']['user'][0]) ? $userinfo[$dataArr['remarks']['user'][0]] : $remarks,
                        'mobile'=>isset($dataArr['mobile']['user'][0]) ? $userinfo[$dataArr['mobile']['user'][0]] : $userinfo['mobile'],
                        'industry'=>isset($dataArr['industry']['user'][0]) ? $userinfo[$dataArr['industry']['user'][0]] : '',
                        'address'=>isset($dataArr['address']['user'][0]) ? $userinfo[$dataArr['address']['user'][0]] : '',
                        'address_detail'=>isset($dataArr['address_detail']['user'][0]) ? $userinfo[$dataArr['address_detail']['user'][0]] : '',
                        'create_staff_id'=>$staff_id,
                        'owner_staff_id'=>$staff_id,
                    );
                    foreach($dataArr as $k=>$v){
                        if(strpos($k,'other_') !== false){
                            $oterinfo[] = array(
                                'key'=>$k,
                                'value'=>$userinfo[$v['user'][0]]
                            );
                        }
                    }
                }else{
                    $lead =array(
                        'name'=>$userinfo['username'],
                        'sex'=>$userinfo['gender'],
                        'level'=>$userinfo['level'],
                        'source'=>$source,
                        'remarks'=>$remarks,
                        'mobile'=>$userinfo['mobile'],
                         'create_staff_id'=>$staff_id,
                        'owner_staff_id'=>$staff_id,
                    );
                }

                $resultlea = Leads::create($lead);
                if(!$resultlea){
                    Db::rollback();
                    $this->error('同步失败');
                }
                $insetId = Leads::getLastInsID();
                if($oterinfo){
                    $oterinfo = array_column($oterinfo,'value','key');
                    $oterinfo = json_encode($oterinfo,JSON_UNESCAPED_UNICODE);
                    $resoter = array(
                        'id'=> $insetId,
                        'otherdata'=>$oterinfo
                    );
                    LeadsOther::create($resoter);
                }
            }
            $fauser = array(
                'user_id'=>$ids,
                'staff_id'=>$staff_id,
                'relation_id'=>$insetId,
                'type'=>$type,
                'status'=>1,
            );
            $resultUse = FauserModel::create($fauser);
            if(!$resultUse){
                Db::rollback();
                $this->error('同步失败');
            }
            Db::commit();
            $this->success('同步成功');
        }
        $follow= Field::getField('客户来源');
        $staff=Staff::where(array('status'=>1))->field('name,id')->select();
        $fieldlist = Form::getDataValue('customer');
        foreach($fieldlist as $k=>$v){
            if($v['id'] =='name' || $v['id'] =='level' || $v['id'] =='source'){
                unset($fieldlist[$k]);
            }
        }
        $column = $this->get_db_column_comment('user');
        $userinfo = Db::getTableInfo('fa_user','fields');
        foreach($userinfo as $k=>$v){
            if($v =='id' || $v =='group_id' || $v =='username' || $v =='nickname' || $v == 'password' || $v =='salt' || $v =='avatar' || $v =='successions' || $v =='maxsuccessions' || $v =='prevtime' || $v =='logintime'
                || $v =='loginfailure' || $v =='token' || $v =='status' || $v =='verification'){
                unset($userinfo[$k]);
                continue;
            }
            if(key_exists($v,$column)){
                $userinfo[$k] = array(
                    'key'=>$v,
                    'value'=>$column[$v]
                );
            }else{
                unset($userinfo[$k]);
            }
        }

        $this->assign('form_data', $fieldlist);
        $this->assign('user_data', $userinfo);
        $this->view->assign('follow', $follow);
        $this->view->assign('staff', $staff);
        return $this->view->fetch();
    }
    /**
     * 批量同步
     */
    public function batch(){

        if ($this->request->isPost()) {
            $data             = $this->request->post('row/a');
            $dataArr             = $this->request->post('rows/a');
            $idinfo = $data['idinfo'];
            $typeinfo = $data['typeinfo'];
            $type = $data['type'];
            $source =$data['source'];
            $staff_id = $data['staff_id'];
            $remarks = '';
            //选中
            if($typeinfo == 1){
                $where['id'] = array('in',$idinfo);
                $userinfo = $this->model->where($where)->select();
            }else{
                //全部
                $fauseronfo =FauserModel::column('user_id');
                if($fauseronfo){
                    $where['id'] =array('not in',implode(',',$fauseronfo));
                    $where['status'] = 'normal';
                    $userinfo = $this->model->where($where)->select();
                }else{
                    $userinfo = $this->model->where(array('status'=>'normal'))->select();
                }
            }
            if(!$userinfo){
                $this->error('无同步数据');
            }
            Db::startTrans();
            foreach($userinfo as $k=>$v){
                $oterinfo = array();
                //客户
                if($type == 0){
                    if($dataArr){
                        if(isset($dataArr['contract_status']['user'][0])){
                            $v[$dataArr['contract_status']['user'][0]] = is_numeric($v[$dataArr['contract_status']['user'][0]]) ? $v[$dataArr['contract_status']['user'][0]] : 0;
                        }

                        $coutomer =array(
                            'name'=>isset($dataArr['name']['user'][0]) ? $v[$dataArr['name']['user'][0]] :$v['username'],
                            'subname'=>isset($dataArr['subname']['user'][0]) ? $v[$dataArr['subname']['user'][0]] : $v['nickname'],
                            'level'=>isset($dataArr['level']['user'][0]) ? $v[$dataArr['level']['user'][0]] : $v['level'],
                            'source'=>isset($dataArr['source']['user'][0]) ? $v[$dataArr['source']['user'][0]] : $source,
                            'contract_status'=>isset($dataArr['contract_status']['user'][0]) ? $v[$dataArr['contract_status']['user'][0]] : 0,
                            'industry'=>isset($dataArr['industry']['user'][0]) ? $v[$dataArr['industry']['user'][0]] : '',
                            'create_staff_id'=>$staff_id,
                            'owner_staff_id'=>$staff_id,
                        );

                        foreach($dataArr as $ks=>$vs){
                            if(strpos($ks,'other_') !== false){
                                $oterinfo[] = array(
                                    'key'=>$ks,
                                    'value'=>$v[$vs['user'][0]]
                                );
                            }
                        }

                    }else{
                        $coutomer =array(
                            'name'=>$v['username'],
                            'subname'=>$v['nickname'],
                            'level'=>$v['level'],
                            'source'=>$source,
                            'remarks'=>$remarks,
                            'create_staff_id'=>$staff_id,
                            'owner_staff_id'=>$staff_id,
                        );
                    }



                    $resultCus = Customer::create($coutomer);
                    if(!$resultCus){
                        Db::rollback();
                        $this->error('同步失败');
                    }
                    $insetId = Customer::getLastInsID();
                    if($oterinfo){
                        $oterinfo = array_column($oterinfo,'value','key');
                        $oterinfo = json_encode($oterinfo,JSON_UNESCAPED_UNICODE);
                        $resoter = array(
                            'id'=> $insetId,
                            'otherdata'=>$oterinfo
                        );
                        CustomerOther::create($resoter);
                    }
                    $contacts = array(
                        'customer_id'=>$insetId,
                        'is_major'=>1,
                        'name'=>$v['username'],
                        'subname'=>$v['nickname'],
                        'email'=>$v['email'],
                        'mobile'=>$v['mobile'],
                        'create_staff_id'=>$staff_id,
                        'owner_staff_id'=>$staff_id,
                    );
                    $resultCon = Contacts::create($contacts);
                    if(!$resultCon){
                        Db::rollback();
                        $this->error('同步失败');
                    }

                }else{

                    if($dataArr){
                        if(isset($dataArr['gender']['user'][0])){
                            $v[$dataArr['gender']['user'][0]] = is_numeric($v[$dataArr['gender']['user'][0]]) ? $v[$dataArr['gender']['user'][0]] : 0;
                        }
                        if(isset($dataArr['level']['user'][0])){
                            $v[$dataArr['level']['user'][0]] = is_numeric($v[$dataArr['level']['user'][0]]) ? $v[$dataArr['level']['user'][0]] : 0;
                        }
                        $lead =array(
                            'name'=>isset($dataArr['name']['user'][0]) ? $v[$dataArr['name']['user'][0]] : $v['username'],
                            'sex'=>isset($dataArr['gender']['user'][0]) ? $v[$dataArr['gender']['user'][0]] : $v['gender'],
                            'level'=>isset($dataArr['level']['user'][0]) ? $v[$dataArr['level']['user'][0]] : $v['level'],
                            'source'=>isset($dataArr['source']['user'][0]) ? $v[$dataArr['source']['user'][0]] : $source,
                            'remarks'=>isset($dataArr['remarks']['user'][0]) ? $v[$dataArr['remarks']['user'][0]] : $remarks,
                            'mobile'=>isset($dataArr['mobile']['user'][0]) ? $v[$dataArr['mobile']['user'][0]] : $v['mobile'],
                            'industry'=>isset($dataArr['industry']['user'][0]) ? $v[$dataArr['industry']['user'][0]] : '',
                            'address'=>isset($dataArr['address']['user'][0]) ? $v[$dataArr['address']['user'][0]] : '',
                            'address_detail'=>isset($dataArr['address_detail']['user'][0]) ? $v[$dataArr['address_detail']['user'][0]] : '',
                            'create_staff_id'=>$staff_id,
                            'owner_staff_id'=>$staff_id,
                        );
                        foreach($dataArr as $ks=>$vs){
                            if(strpos($ks,'other_') !== false){
                                $oterinfo[] = array(
                                    'key'=>$ks,
                                    'value'=>$v[$vs['user'][0]]
                                );
                            }
                        }
                    }else{
                        //线索
                        $lead =array(
                            'name'=>$v['username'],
                            'sex'=>$v['gender'],
                            'level'=>$v['level'],
                            'source'=>$source,
                            'remarks'=>$remarks,
                            'mobile'=>$v['mobile'],
                            'create_staff_id'=>$staff_id,
                            'owner_staff_id'=>$staff_id,
                        );
                    }


                    $resultlea = Leads::create($lead);
                    if(!$resultlea){
                        Db::rollback();
                        $this->error('同步失败');
                    }
                    $insetId = Leads::getLastInsID();
                    if($oterinfo){
                        $oterinfo = array_column($oterinfo,'value','key');
                        $oterinfo = json_encode($oterinfo,JSON_UNESCAPED_UNICODE);
                        $resoter = array(
                            'id'=> $insetId,
                            'otherdata'=>$oterinfo
                        );
                        LeadsOther::create($resoter);
                    }
                }
                $fauser = array(
                    'user_id'=>$v['id'],
                    'staff_id'=>$staff_id,
                    'relation_id'=>$insetId,
                    'type'=>$type,
                    'status'=>1,
                );
                $resultUse = FauserModel::create($fauser);
                if(!$resultUse){
                    Db::rollback();
                    $this->error('同步失败');
                }
            }
            Db::commit();
            $this->success('同步成功');
        }
        $idinfo = input('id');
        $typeinfo = input('type');
        $follow= Field::getField('客户来源');
        $staff=Staff::where(array('status'=>1))->field('name,id')->select();

        $fieldlist = Form::getDataValue('customer');
        foreach($fieldlist as $k=>$v){
            if($v['id'] =='name' || $v['id'] =='level' || $v['id'] =='source'){
                unset($fieldlist[$k]);
            }
        }
        $column = $this->get_db_column_comment('user');
        $userinfo = Db::getTableInfo('fa_user','fields');
        foreach($userinfo as $k=>$v){
            if($v =='id' || $v =='group_id' || $v =='username' || $v =='nickname' || $v == 'password' || $v =='salt' || $v =='avatar' || $v =='successions' || $v =='maxsuccessions' || $v =='prevtime' || $v =='logintime'
                || $v =='loginfailure' || $v =='token' || $v =='status' || $v =='verification'){
                unset($userinfo[$k]);
                continue;
            }
            if(key_exists($v,$column)){
                $userinfo[$k] = array(
                    'key'=>$v,
                    'value'=>$column[$v]
                );
            }else{
                unset($userinfo[$k]);
            }
        }

        $this->assign('form_data', $fieldlist);
        $this->assign('user_data', $userinfo);
        $this->view->assign('follow', $follow);
        $this->view->assign('staff', $staff);
        $this->view->assign('idinfo', $idinfo);
        $this->view->assign('typeinfo', $typeinfo);
        return $this->view->fetch();
    }
    /**
     * 获取来源
     */
    public function source(){
        $type = input('type','0');
        //客户
        if($type == 0){
            $follow= Field::getField('客户来源');
        }else{
            $follow= Field::getField('线索来源');
        }
        $this->success('请求成功','',$follow);
    }

    /**
     * 获取数据库字段注释
     *
     * @param string $table_name 数据表名称(必须，不含前缀)
     * @param string $field 字段名称(默认获取全部字段,单个字段请输入字段名称)
     * @param string $table_schema 数据库名称(可选)
     * @return string
     */
    public function get_db_column_comment($table_name = '', $field = true, $table_schema = ''){

        // 接收参数

        $database = config('database');

        $table_schema = empty($table_schema) ? $database['database'] : $table_schema;

        $table_name = $database['prefix'] . $table_name;

        // 缓存名称

        $fieldName = $field === true ? 'allField' : $field;

        $cacheKeyName = 'db_' . $table_schema . '_' . $table_name . '_' . $fieldName;

        // 处理参数

        $param = [

            $table_name,

            $table_schema

        ];

        // 字段

        $columeName = '';

        if($field !== true){

        $param[] = $field;

        $columeName = "AND COLUMN_NAME = ?";

        }
        // 查询结果
        $result = Db :: query("SELECT COLUMN_NAME as field,column_comment as comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ? AND table_schema = ? $columeName", $param);

        // 处理结果
        $data = [];
        foreach($result as $k => $v){

            $data[$v['field']] = $v['comment'];

        }
        return $data;

    }

    /**
     * 客户、线索字段
     */
    public function fieldinfo(){
        $type= input('type',0);
        if($type == 1){
            $typename = 'leads';
        }else{
            $typename = 'customer';
        }
        $fieldlist = Form::getDataValue($typename);
        foreach($fieldlist as $k=>$v){
            if($v['id'] =='remarks'){
                unset($fieldlist[$k]);
            }
        }
        $fieldlist = array_values($fieldlist);
        $this->success('请求成功','',$fieldlist);
    }
    /**
     * 会员字段
     */
    public function fielduser(){
        $column = $this->get_db_column_comment('user');
        $userinfo = Db::getTableInfo('fa_user','fields');
        foreach($userinfo as $k=>$v){
            if($v =='id' || $v =='group_id'  || $v == 'password' || $v =='salt' || $v =='avatar' || $v =='successions' || $v =='maxsuccessions' || $v =='prevtime' || $v =='logintime'
                || $v =='loginfailure' || $v =='token' || $v =='status' || $v =='verification'){
                unset($userinfo[$k]);
                continue;
            }
            if(key_exists($v,$column)){
                $userinfo[$k] = array(
                    'key'=>$v,
                    'value'=>$column[$v]
                );
            }else{
                unset($userinfo[$k]);
            }
        }
        $userinfo = array_values($userinfo);
        $this->success('请求成功','',$userinfo);
    }


}
